#!/bin/bash
set -e

echo "🔧 开始服务器环境配置..."

# 检查是否为 root 用户
if [[ $EUID -ne 0 ]]; then
   echo "❌ 请使用 root 用户运行此脚本"
   exit 1
fi

# 更新系统
echo "📦 更新系统包..."
apt update && apt upgrade -y

# 安装基础软件
echo "📦 安装基础软件..."
apt install -y nginx mysql-server git curl build-essential

# 配置防火墙
echo "🔥 配置防火墙..."
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw --force enable

# 启动并启用服务
echo "🚀 启动服务..."
systemctl start nginx mysql
systemctl enable nginx mysql

# 创建部署用户 (如果不存在)
if ! id "deploy" &>/dev/null; then
    echo "👤 创建部署用户..."
    useradd -m -s /bin/bash deploy
    usermod -aG sudo deploy
    echo "请为 deploy 用户设置密码:"
    passwd deploy
fi

# 创建项目目录
echo "📁 创建项目目录..."
mkdir -p /var/www/dx-fun-group
chown deploy:deploy /var/www/dx-fun-group

# 配置 Node.js (为 deploy 用户)
echo "📦 为 deploy 用户配置 Node.js..."
sudo -u deploy bash << 'EOF'
cd ~
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm install 20
nvm use 20
npm install -g pnpm pm2
echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.bashrc
echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> ~/.bashrc
echo '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"' >> ~/.bashrc
EOF

# MySQL 安全配置提示
echo "🔒 MySQL 安全配置..."
echo "请运行以下命令完成 MySQL 配置:"
echo "sudo mysql_secure_installation"
echo ""
echo "然后创建数据库用户:"
echo "sudo mysql -u root -p"
echo "CREATE DATABASE dx_fun_group;"
echo "CREATE USER 'dx_user'@'localhost' IDENTIFIED BY 'your_password';"
echo "GRANT ALL PRIVILEGES ON dx_fun_group.* TO 'dx_user'@'localhost';"
echo "FLUSH PRIVILEGES;"
echo "EXIT;"

echo "✅ 服务器环境配置完成！"
echo "下一步:"
echo "1. 切换到 deploy 用户: su - deploy"
echo "2. 克隆项目到 /var/www/dx-fun-group"
echo "3. 按照 DEPLOY.md 继续配置"
